package com.study.jyg.rxjava2study.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import androidx.annotation.Nullable;
import android.util.Log;

import com.study.jyg.rxjava2study.event.GetStartAppTimeEvent;
import com.study.jyg.rxjava2study.event.StartAppTimeEvent;
import com.study.jyg.rxjava2study.utils.MyMath;
import com.study.jyg.rxjava2study.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Calendar;
import java.util.Random;
import java.util.TimeZone;

public class StartAppService extends Service {

    private Handler mHandler;
    private Runnable mRunnable;
    private int rondom;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("service", "onCreate");
        initHandler();
        EventBus.getDefault().register(this);
    }

    @Subscribe
    public void getStartTime(GetStartAppTimeEvent e) {
        EventBus.getDefault().post(new StartAppTimeEvent(rondom));
    }

    private void initHandler() {
        rondom = MyMath.random(9);
        EventBus.getDefault().post(new StartAppTimeEvent(rondom));
        mHandler = new Handler();
        mRunnable = () -> {
            Log.e("rondom", "rondom = " + rondom);
            Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);
            int week = calendar.get(Calendar.DAY_OF_WEEK);
            if (hour == 8 && minute == 50 + rondom && week != 1) {
                rondom = MyMath.random(9);
                try {
                    Intent intent = getPackageManager().getLaunchIntentForPackage("com.alibaba.android.rimet");
                    startActivity(intent);
                    EventBus.getDefault().post(new StartAppTimeEvent(rondom));
                } catch (Exception e) {
                    ToastUtils.show("没有安装DingDingApp");
                }
            }
            mHandler.postDelayed(mRunnable, 1000);
        };
        mHandler.post(mRunnable);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
